package org.source.code.collection.map.hashMap;

import org.cleaver.basic.annotations.Important;
import sun.misc.SharedSecrets;

import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * JDK1.8之HashMap源码分析
 *
 * @author LiKun
 * @date 2021/10/19 10:45
 */
public class HashMapSource<K, V> extends AbstractMapSource<K, V> implements Map<K, V>, Cloneable, Serializable {

    /**
     * 使用树而不是列表的 bin 计数阈值。将元素添加到至少具有这么多节点的 bin 时，bin 会转换为树。
     * 该值必须大于 2 且至少应为 8，以与树移除中关于在收缩时转换回普通 bin 的假设相匹配。
     */
    static final int TREEIFY_THRESHOLD = 8;

    /*
     * 实施说明。
     *
     * 该映射通常用作分箱（分桶）哈希表，但是当分箱变得太大时，它们会被转换为 TreeNode 的分箱，每个分箱的结构类似于 java.util.TreeMap 中的分箱。
     * 大多数方法尝试使用普通 bins，但在适用时中继到 TreeNode 方法（简单地通过检查节点的实例）。
     * TreeNodes 的 bins 可以像任何其他 bins 一样被遍历和使用，但另外支持在人口过多时更快的查找。
     * 然而，由于绝大多数正常使用的 bin 并没有过度填充，因此在 table 方法的过程中检查树 bin 的存在可能会延迟。
     *
     * 树箱（即元素都是 TreeNode 的箱）主要按 hashCode 排序，但在 tie 的情况下，如果两个元素是相同的 “C 类实现 Comparable<C>”，
     * 则输入它们的 compareTo 方法订购。 （我们通过反射保守地检查泛型类型以验证这一点——参见方法可比较ClassFor）。
     * 当键具有不同的散列或可排序时，树箱的增加的复杂性值得提供最坏情况的 O(log n) 操作，
     * 因此，在 hashCode() 方法返回的值很差的意外或恶意使用下，性能会优雅地降低分布式，以及其中许多键共享一个 hashCode 的那些，
     * 只要它们也是 Comparable 的。（如果这些都不适用，与不采取预防措施相比，我们可能会在时间和空间上浪费大约两倍。
     * 但唯一已知的情况源于糟糕的用户编程实践，这些实践已经很慢，这几乎没有什么区别。）
     *
     * 因为 TreeNode 的大小大约是常规节点的两倍，所以我们仅在 bin 包含足够多的节点以保证使用时才使用它们（请参阅 TREEIFY_THRESHOLD）。
     * 当它们变得太小（由于移除或调整大小）时，它们会被转换回普通垃圾箱。在使用分布良好的用户哈希码的情况下，很少使用树箱。
     * 理想情况下，在随机 hashCodes 下，bins 中节点的频率遵循泊松分布 (http:en.wikipedia.orgwikiPoisson_distribution)，
     * 对于默认调整大小阈值 0.75，参数平均约为 0.5，尽管由于调整大小粒度而存在很大差异.忽略方差，
     * 列表大小 k 的预期出现次数为 (exp(-0.5) pow(0.5, k) factorial(k))。第一个值是：
     *
     * 0:    0.60653066
     * 1:    0.30326533
     * 2:    0.07581633
     * 3:    0.01263606
     * 4:    0.00157952
     * 5:    0.00015795
     * 6:    0.00001316
     * 7:    0.00000094
     * 8:    0.00000006
     * 更多：不到千万分之一
     *
     * 树箱的根通常是它的第一个节点。然而，有时（目前仅在 Iterator.remove 上），根可能在别处，但可以通过父链接（方法 TreeNode.root()）恢复。
     *
     * 所有适用的内部方法都接受一个哈希码作为参数（通常由公共方法提供），允许它们相互调用而无需重新计算用户哈希码。
     * 大多数内部方法也接受一个“tab”参数，它通常是当前表，但在调整大小或转换时可能是新的或旧的。
     *
     * 当 bin 列表被树化、拆分或未树化时，我们将它们保持在相同的相对访问遍历顺序（即字段 Node.next）中，以更好地保留局部性，
     * 并稍微简化调用 iterator.remove 的拆分和遍历的处理。在插入时使用比较器时，为了在重新平衡之间保持总排序（或尽可能接近此处的要求），
     * 我们将类和 identityHashCodes 作为决胜局进行比较。
     *
     * 由于子类 LinkedHashMap 的存在，普通模式与树模式之间的使用和转换变得复杂。请参阅下文，了解定义为在插入、删除和访问时调用的钩子方法，
     * 这些方法允许 LinkedHashMap 内部以其他方式保持独立于这些机制。 （这还要求将map实例传递给一些可能创建新节点的实用程序方法。）
     *
     * 类似于并发编程的基于 SSA 的编码风格有助于避免在所有扭曲指针操作中出现混叠错误。
     */
    /**
     * 在调整大小操作期间取消（拆分）bin 的 bin 计数阈值。应小于 TREEIFY_THRESHOLD，最多为 6 以在移除下进行收缩检测。
     */
    static final int UNTREEIFY_THRESHOLD = 6;

    /**
     * 红黑树节点的最大个数阈值，超过则会进行扩容操作
     * 可以将 bin 树化的最小表容量。（否则，如果 bin 中的节点过多，则表将调整大小。）应至少为 4 * TREEIFY_THRESHOLD，以避免调整大小和树化阈值之间发生冲突。
     */
    static final int MIN_TREEIFY_CAPACITY = 64;

    /**
     * 最大容量，在两个带参数的构造函数中的任何一个隐式指定更高的值时使用。必须是 2 的幂 <= 1<<30。
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

    /**
     * 在构造函数中未指定时使用的负载因子(默认的负载因子，一般不建议修改)。
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    /**
     * 默认初始容量 - 必须是 2 的幂。
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;

    private static final long serialVersionUID = 362498820763181265L;

    /**
     * 哈希表的负载因子。
     *
     * @serial
     */
    final float loadFactor;

    /* ---------------- 静态实用程序 -------------- */
    /**
     * 初始化时的容量 || 要调整大小的下一个大小值（容量负载因子） || 触发扩容操作的阈值。
     * <p>
     * （描述在序列化时为真。此外，如果尚未分配表数组，则此字段保存初始数组容量，或零表示 DEFAULT_INITIAL_CAPACITY。）
     */
    int threshold;

    /**
     * 此映射中包含的键值映射数。
     */
    transient int size;

    /**
     * 此 HashMapSource 被结构修改的次数该字段用于在 HashMapSource 的 Collection-views 上创建迭代器快速失败。（请参阅 ConcurrentModificationException）。
     */
    transient int modCount;

    /**
     * 表，在第一次使用时初始化，并根据需要调整大小。分配时，长度始终是 2 的幂。（我们还在某些操作中容忍长度为零，以允许当前不需要的引导机制。）
     */
    transient Node<K, V>[] table;

    /* ---------------- 相关字段 -------------- */
    /**
     * 保存缓存的 entrySet()。请注意，AbstractMap 字段用于 keySet() 和 values()。
     */
    transient Set<Entry<K, V>> entrySet;

    /**
     * 使用默认初始容量 (16) 和默认负载因子 (0.75) 构造一个空的 HashMapSource。
     */
    public HashMapSource() {
        this.loadFactor = DEFAULT_LOAD_FACTOR;                                    // 所有其他字段默认
    }

    /**
     * 使用指定的初始容量和默认加载因子 (0.75) 构造一个空的 HashMapSource。
     *
     * @param initialCapacity 初始容量。
     *
     * @throws IllegalArgumentException 如果初始容量为负。
     */
    public HashMapSource(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    /**
     * 使用与指定的 Map 相同的映射构造一个新的 HashMapSource。
     * HashMapSource 是使用默认加载因子 (0.75) 和足以在指定的 Map 中保存映射的初始容量创建的。
     *
     * @param map 要在此map中放置其映射的map
     *
     * @throws NullPointerException 如果指定的map为空
     */
    public HashMapSource(Map<? extends K, ? extends V> map) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(map, false);
    }

    /**
     * 使用指定的初始容量和负载因子构造一个空的 HashMapSource。
     *
     * @param initialCapacity 初始容量
     * @param loadFactor      负载系数
     *
     * @throws IllegalArgumentException 如果初始容量为负或负载因子为非正
     */
    public HashMapSource(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0) {
            throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);
        }
        // 指定的容量不能超出最大容量限制
        if (initialCapacity > MAXIMUM_CAPACITY) {
            initialCapacity = MAXIMUM_CAPACITY;
        }
        if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
            throw new IllegalArgumentException("Illegal load factor: " + loadFactor);
        }
        this.loadFactor = loadFactor;
        // 将给定的容量向上取整初始化为 2 ^ n
        this.threshold = tableSizeFor(initialCapacity);
    }

    /**
     * 扰动函数
     * <p>
     * 计算 key.hashCode() 并将散列的较高位（异或）传播到较低位。由于该表使用二次幂掩码，因此仅在当前掩码之上位变化的散列集将始终发生冲突。
     * （众所周知的例子是在小表中保存连续整数的浮点键集。）所以我们应用了一种向下传播高位影响的变换。位扩展的速度、效用和质量之间存在权衡。
     * 因为许多常见的散列集已经合理分布（因此不会从传播中受益），并且因为我们使用树来处理 bin 中的大量冲突，
     * 所以我们只是以最便宜的方式对一些移位的位进行异或以减少系统损失，以及合并最高位的影响，否则由于表边界而永远不会在索引计算中使用。
     */
    static int hash(Object key) {
        int h;
        // 目的：尽可能地加大低位的随机性以降低哈希冲突
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

    /* ---------------- 公共的构造函数 -------------- */

    /**
     * 如果 x 的类的形式为“类 C 实现 Comparable<C>”，则返回 x 的类，否则返回 null。
     */
    static Class<?> comparableClassFor(Object obj) {
        if (obj instanceof Comparable) {
            Type t;
            Type[] types, typeArr;
            Class<?> aClass = obj.getClass();
            ParameterizedType parameterizedType;
            if (aClass == String.class) {
                return aClass;
            } else {
                // aClass.getGenericInterfaces()：返回该Class实现的接口类型
                if ((types = aClass.getGenericInterfaces()) != null) {
                    for (Type typeEach : types) {
                        if (((t = typeEach) instanceof ParameterizedType) &&
                                ((parameterizedType = (ParameterizedType) t).getRawType() == Comparable.class) &&
                                (typeArr = parameterizedType.getActualTypeArguments()) != null && typeArr.length == 1 && typeArr[0] == aClass)  // 类型 arg 是 aClass
                        {
                            return aClass;
                        }
                    }
                }
            }
        }
        return null;
    }

    /**
     * 如果 x 匹配 kc（k 的筛选可比类），则返回 k.compareTo(x)，否则返回 0。
     */
    @SuppressWarnings({"rawtypes"}) // 用于可比较的转换
    static int compareComparables(Class<?> kc, Object k, Object x) {
        return (x == null || x.getClass() != kc ? 0 : ((Comparable) k).compareTo(x));
    }

    /**
     * 将给定的cap向上取整到2的n次幂
     * 返回给定目标容量的二次幂。
     */
    @Important("将给定的值向上取整到2的n次幂")
    public static int tableSizeFor(int cap) {
        int n = cap - 1;              // 目的：(cap == 2 ^ n) ? cap : tableSizeFor(cap)。例如：当cap为8，则返回8；如果不添加该行代码，则会返回16
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

    /**
     * 实现 putAll 和 Map 构造函数。
     *
     * @param map   the map
     * @param evict 最初构造此映射时为 false，否则为 true（中继到方法 afterNodeInsertion）。
     */
    @Important
    final void putMapEntries(Map<? extends K, ? extends V> map, boolean evict) {
        int size = map.size();
        if (size > 0) {
            if (table == null) {                                  // 初始化数组空间
                // + 1.0F 进行扩容(可能是为了避免下次添加数据时触发扩容操作)
                float initialSize = ((float) size / loadFactor) + 1.0F;
                int initialSize2Int = (initialSize < (float) MAXIMUM_CAPACITY) ? (int) initialSize : MAXIMUM_CAPACITY;

                if (initialSize2Int > threshold) {
                    // 将给定的initialSize2Int向上取整到2的n次幂
                    threshold = HashMapSource.tableSizeFor(initialSize2Int);
                }
            } else if (size > threshold) {
                this.resize();                          // 触发扩容操作
            }
            // 遍历存放数据
            for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
                K key = entry.getKey();
                V value = entry.getValue();
                this.putVal(HashMapSource.hash(key), key, value, false, evict);
            }
        }
    }

    /**
     * Returns the number of key-value mappings in this map.
     *
     * @return the number of key-value mappings in this map
     */
    @Override
    public int size() {
        return size;
    }

    /**
     * Returns true</tt> if this map contains no key-value mappings.
     *
     * @return true</ tt> if this map contains no key-value mappings
     */
    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * Returns the value to which the specified key is mapped,
     * or {@code null} if this map contains no mapping for the key.
     *
     * <p>More formally, if this map contains a mapping from a key
     * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
     * key.equals(k))}, then this method returns {@code v}; otherwise
     * it returns {@code null}.  (There can be at most one such mapping.)
     *
     * <p>A return value of {@code null} does not <i>necessarily</i>
     * indicate that the map contains no mapping for the key; it's also
     * possible that the map explicitly maps the key to {@code null}.
     * The {@link #containsKey containsKey} operation may be used to
     * distinguish these two cases.
     *
     * @see #put(Object, Object)
     */
    @Override
    public V get(Object key) {
        Node<K, V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

    /**
     * 实现 get 和相关方法。
     *
     * @param hash 密钥的散列
     * @param key  key
     *
     * @return 节点，如果没有，则为 null
     */
    final Node<K, V> getNode(int hash, Object key) {
        K k;
        int n;
        Node<K, V>[] tab;
        Node<K, V> first, node;
        // 检查数组是否为空 && 数组中是否含有数据 && 该索引位置是否含有数据
        if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) {
            // 检查第一个结点的key值是否等于给定的key值
            if (first.hash == hash && ((k = first.key) == key || (key != null && key.equals(k)))) {
                return first;
            }
            if ((node = first.next) != null) {                         // 检查之后节点的key值
                if (first instanceof TreeNode) {                       // 该节点是否为红黑树节点
                    return ((TreeNode<K, V>) first).getTreeNode(hash, key);
                }
                do {                                       // 遍历剩余的节点数据找出给定的key值
                    if (node.hash == hash && ((k = node.key) == key || (key != null && key.equals(k)))) {
                        return node;
                    }
                } while ((node = node.next) != null);
            }
        }
        return null;
    }

    /**
     * 如果此映射包含指定键的映射，则返回 true。
     *
     * @param key 要测试其在此map中是否存在的密钥
     *
     * @return true 如果此映射包含指定的映射
     * key.
     */
    @Override
    public boolean containsKey(Object key) {
        return getNode(hash(key), key) != null;
    }

    /**
     * 将指定值与此映射中的指定键相关联。如果映射先前包含键的映射，则旧值将被替换。
     *
     * @param key   与指定值相关联的键
     * @param value 要与指定键关联的值
     *
     * @return 与 key 关联的先前值，如果 key 没有映射，则为 null。（null 返回也可以表明映射先前将 null 与 key 关联。）
     */
    @Override
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    /**
     * 实现 put 和相关方法。
     * <p>
     * 存放数据前不需要校验空间容量是否足够的原因: 1.如果数组为进行时初始化，则初始化数组(不会发生溢出)；
     * 2.loadFactor >= 1，数组会退化为链表；
     * 3.loadFactor < 1，初始化后 capacity >= 1 && threshold >= 0，放入第一个数据后会判断 size > threshold 并进行扩容
     *
     * @param hash         key的散列
     * @param key          key
     * @param value        要放置的值
     * @param onlyIfAbsent 如果为 true，则不要更改现有值
     * @param evict        如果为 false，则表处于创建模式。
     *
     * @return 以前的值，如果没有，则为 null
     */
    @Important
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
        int n, i;
        Node<K, V> oldNode;
        Node<K, V>[] tempTable;
        // 当table为空时，则触发其初始化操作
        if ((tempTable = table) == null || (n = tempTable.length) == 0) {
            n = (tempTable = this.resize()).length;
        }

        /* 当 b = 2 ^ x 时，a % b = a & (b - 1) */
        if ((oldNode = tempTable[i = hash & (n - 1)]) == null) {
            tempTable[i] = newNode(hash, key, value, null);
        } else {
            K k;
            Node<K, V> node;
            // 比较 要插入的key 与 存在的key 是否相等
            if (oldNode.hash == hash && ((k = oldNode.key) == key || (key != null && key.equals(k)))) {
                node = oldNode;
            } else if (oldNode instanceof TreeNode) {                        // 判断该节点是否为红黑树
                node = ((TreeNode<K, V>) oldNode).putTreeVal(this, tempTable, hash, key, value);
            } else {                                                         // 普通链表节点添加
                for (int binCount = 0; ; ++binCount) {                       // 遍历该哈希值下的链表
                    if ((node = oldNode.next) == null) {                     // 遍历到最后一个节点 && node == null
                        oldNode.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) {             // 判断该链表是否支持转为红黑树，当现存结点个数为：8
                            this.treeifyBin(tempTable, hash);                // 当 底层数组容量 > MIN_TREEIFY_CAPACITY 才会将节点转为红黑树，否则将会进行扩容
                        }
                        break;
                    }
                    // 判断该链表中节点的key是否与给定的key相等
                    if (node.hash == hash && ((k = node.key) == key || (key != null && key.equals(k)))) {
                        break;                                     // node != null；对值的替换将会在下一个 if 判断中进行
                    }
                    oldNode = node;
                }
            }

            if (node != null) {                                     // 存在键的现有映射
                V oldValue = node.value;
                if (!onlyIfAbsent || oldValue == null) {
                    node.value = value;
                }
                afterNodeAccess(node);
                return oldValue;                                   // 没有修改现有数据结构(返回旧值)
            }
        }

        ++modCount;                                                // 数据结构被修改的次数 + 1
        if (++size > threshold) {                                  // 当 HashMap 中的数据的键值对大于阈值，则出发扩容机制
            this.resize();
        }
        afterNodeInsertion(evict);
        return null;
    }

    /**
     * 扩容一倍(默认情况下)
     * <p>
     * 初始化或加倍表大小。如果为空，则根据字段阈值中持有的初始容量目标进行分配。否则，因为我们使用的是 2 的幂扩展，
     * 所以每个 bin 中的元素必须保持相同的索引，或者在新表中以 2 的幂的偏移量移动。
     *
     * @return table 扩容后的数组
     */
    @Important("将底层数组的容量扩容一倍")
    final Node<K, V>[] resize() {
        int oldThr = threshold;
        int newCap, newThr = 0;
        Node<K, V>[] oldTab = table;
        // 当前底层数组的容量大小
        int oldCap = (oldTab == null) ? 0 : oldTab.length;

        if (oldCap > 0) {                               // 当前 HashMap 是否为空
            if (oldCap >= MAXIMUM_CAPACITY) {                           // HashMap 已达到最大容量
                threshold = Integer.MAX_VALUE;
                return oldTab;
            } else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) {       // 容量 * 2; 判断 oldCap >= DEFAULT_INITIAL_CAPACITY 的原因是 oldCap * loadFactor << 1 的误差较大
                newThr = oldThr << 1;                   // 阈值 * 2
            }
        } else if (oldThr > 0) {                        // 数组未被初始化 && 有初始容量，初始容量被置于阈值；注：该情况较常见
            newCap = oldThr;
        } else {                                        // 零初始阈值表示使用默认值 && 无初始容量；注：该情况最常见
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int) (DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }

        if (newThr == 0) {                               // 如果没有设置新的阈值，则在此处统一设置为：容量 * 负载因子 || Integer.MAX_VALUE
            float flo = (float) newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && flo < (float) MAXIMUM_CAPACITY ? (int) flo : Integer.MAX_VALUE);
        }
        threshold = newThr;                              // 保存该阈值到 HashMap 中

        /*---------------------------将原数据重新放置到扩容后的数组中--------------------------*/

        table = (Node<K, V>[]) new Node[newCap];
        if (oldTab != null) {                                      // 该处不会出现 oldCap >= newCap 的情况
            for (int j = 0; j < oldCap; ++j) {
                Node<K, V> nodeList;
                if ((nodeList = oldTab[j]) != null) {
                    oldTab[j] = null;
                    if (nodeList.next == null) {                        // 该数组位置只有一个数据，重新计算数组下标并存放
                        table[nodeList.hash & (newCap - 1)] = nodeList;
                    } else if (nodeList instanceof TreeNode) {          // 红黑树节点
                        ((TreeNode<K, V>) nodeList).split(this, table, j, oldCap);
                    } else {                                            // 保持秩序(直译) && 该数组位置存在多个数据，且该数据形式为链表
                        Node<K, V> next;
                        Node<K, V> loHead = null, loTail = null;                        // 数组前半段索引对应链表
                        Node<K, V> hiHead = null, hiTail = null;                        // 数组前后段索引对应链表

                        /*
                         * 注：此情况当且仅当 length == 2 ^ n
                         * 扩容前确认数组索引：hash & (length - 1); 扩容后确认数组索引：hash & (2 * length - 1);
                         * 而 (2 * length - 1) 比 (length - 1) 的区别在于更高一位值为1，在 (xxx & hash) 获得的值取决于该位的 hash 码的值，
                         * 因此存在两种可能：hash & (2 * length - 1) == hash & (length - 1) || hash & (2 * length - 1) == hash & (length - 1) + length
                         */
                        do {                  // 同一个链表中的节点(索引为x)，在分配到新的数组中只有两个地方(一个算法)，x || x + oldCap，拼接成两条新的链表
                            next = nodeList.next;
                            // 结论：当 (nodeList.hash & oldCap) == 0 时，(2oldCap - 1) & node.hash == (oldCap - 1) & node.hash
                            // 结论：当 (nodeList.hash & oldCap) != 0 时，(2oldCap - 1) & node.hash == (oldCap - 1) & node.hash + oldCap

                            // 相关链接：https://blog.csdn.net/weixin_46195957/article/details/125298629
                            if ((nodeList.hash & oldCap) == 0) {                        // 数组的索引不变
                                if (loTail == null) {
                                    loHead = nodeList;
                                } else {
                                    loTail.next = nodeList;
                                }
                                loTail = nodeList;
                            } else {                                                    // 新索引 = 旧索引 + 旧数组长度
                                if (hiTail == null) {
                                    hiHead = nodeList;
                                } else {
                                    hiTail.next = nodeList;
                                }
                                hiTail = nodeList;
                            }
                        } while ((nodeList = next) != null);

                        // 将生成两条链表插入到新的数组中的正确位置
                        if (loTail != null) {                                         // 数组的索引不变
                            loTail.next = null;
                            table[j] = loHead;
                        }
                        if (hiTail != null) {                                         // 新索引 = 旧索引 + 旧数组长度
                            hiTail.next = null;
                            table[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return table;
    }

    /**
     * 当现存数据个数小于 MIN_TREEIFY_CAPACITY 时，不会将链表转换为红黑树，而是进行扩容操作
     * 除非表太小，否则替换给定哈希索引处 bin 中的所有链接节点，在这种情况下改为调整大小。
     */
    @Important
    final void treeifyBin(Node<K, V>[] tab, int hash) {
        int n, index;
        Node<K, V> node;
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY) {            // (数组为空 || 数组的个数 < 64) ---> 触发扩容操作，而不是转换为树
            resize();
        } else if ((node = tab[index = (n - 1) & hash]) != null) {
            TreeNode<K, V> head = null, tail = null;
            do {                                          // 将链表转换为由TreeNode组成的双向链表
                TreeNode<K, V> treeNode = replacementTreeNode(node, null);
                if (tail == null) {
                    head = treeNode;
                } else {
                    treeNode.prev = tail;
                    tail.next = treeNode;
                }
                tail = treeNode;
            } while ((node = node.next) != null);

            if ((tab[index] = head) != null) {
                head.treeify(tab);                                  // 将双向链表转换为红黑树
            }
        }
    }

    /**
     * 将所有映射从指定映射复制到此映射。这些映射将替换此映射对当前在指定映射中的任何键的任何映射。
     *
     * @param map 要存储在此映射中的映射
     *
     * @throws NullPointerException 如果指定的map为空
     */
    @Override
    public void putAll(Map<? extends K, ? extends V> map) {
        putMapEntries(map, true);
    }

    /**
     * 如果存在，则从此映射中删除指定键的映射。
     *
     * @param key 要从映射中删除其映射的键
     *
     * @return 与 key 关联的先前值，如果 key 没有映射，则为 null。（null 返回也可以表明映射先前将 null 与 key 关联。）
     */
    @Override
    public V remove(Object key) {
        Node<K, V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ? null : e.value;
    }

    /**
     * 实现 remove 和相关方法。
     *
     * @param hash       密钥的散列
     * @param key        the key
     * @param value      如果匹配值则匹配的值，否则忽略
     * @param matchValue 如果为真，则仅在值相等时删除
     * @param movable    如果为 false，则在删除时不移动其他节点
     *
     * @return 节点，如果没有，则为 null
     */
    final Node<K, V> removeNode(int hash, Object key, Object value, boolean matchValue, boolean movable) {
        int n, index;
        Node<K, V> p;
        Node<K, V>[] tab;
        if ((tab = table) != null && (n = tab.length) > 0 && (p = tab[index = (n - 1) & hash]) != null) {
            K k;
            V v;
            Node<K, V> node = null, e;
            if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) {
                node = p;
            } else if ((e = p.next) != null) {
                if (p instanceof TreeNode) {
                    node = ((TreeNode<K, V>) p).getTreeNode(hash, key);
                } else {
                    do {
                        if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
            if (node != null && (!matchValue || (v = node.value) == value || (value != null && value.equals(v)))) {
                if (node instanceof TreeNode) {
                    ((TreeNode<K, V>) node).removeTreeNode(this, tab, movable);
                } else if (node == p) {
                    tab[index] = node.next;
                } else {
                    p.next = node.next;
                }
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

    /**
     * 从此映射中删除所有映射。此调用返回后，map将为空。
     */
    @Override
    public void clear() {
        Node<K, V>[] tab;
        modCount++;
        if ((tab = table) != null && size > 0) {
            size = 0;
            for (int i = 0; i < tab.length; ++i) {
                tab[i] = null;
            }
        }
    }

    /**
     * 如果此映射将一个或多个键映射到指定值，则返回 true。
     *
     * @param value 要测试其在此map中是否存在的值
     *
     * @return 如果此映射将一个或多个键映射到指定值，则为 true
     */
    @Override
    public boolean containsValue(Object value) {
        V v;
        Node<K, V>[] tab;

        if ((tab = table) != null && size > 0) {
            for (Node<K, V> node : tab) {
                for (Node<K, V> e = node; e != null; e = e.next) {
                    if ((v = e.value) == value || (value != null && value.equals(v))) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 返回此映射中包含的键的 {@link Set} 视图。该集合由map支持，因此对map的更改会反映在该集合中，反之亦然。
     * 如果在对集合进行迭代时修改了映射（通过迭代器自己的 remove 操作除外），则迭代的结果是不确定的。
     * 该集合支持元素移除，即通过 Iterator.remove、Set.remove、removeAll、retainAll 和 clear 操作从映射中移除相应的映射。
     * 它不支持 add 或 addAll 操作。
     *
     * @return 此映射中包含的键的集合视图
     */
    @Override
    public Set<K> keySet() {
        Set<K> ks = keySet;
        if (ks == null) {
            ks = new KeySet();
            keySet = ks;
        }
        return ks;
    }

    /**
     * 返回此map中包含的值的 {@link Collection} 视图。集合由map支持，因此对map的更改会反映在集合中，反之亦然。
     * 如果在对集合进行迭代时修改了映射（通过迭代器自己的 removemap 操作除外），则迭代的结果是不确定的。
     * 该集合支持元素移除，即通过 Iterator.removemap、Collection.removemap、removeAllmap、retainAllmap 和 clearmap 操作从map中移除相应的映射。
     * 它不支持 addmap 或 addAllmap 操作。
     *
     * @return 此map中包含的值的视图
     */
    @Override
    public Collection<V> values() {
        Collection<V> vs = values;
        if (vs == null) {
            vs = new Values();
            values = vs;
        }
        return vs;
    }

    /**
     * 返回此map中包含的映射的 {@link Set} 视图。该集合由map支持，因此对map的更改会反映在该集合中，反之亦然。
     * 如果在对集合进行迭代时修改了映射（除了通过迭代器自己的 remove 操作，或通过迭代器返回的映射条目上的 setValue 操作），迭代的结果是未定义的.
     * 该集合支持元素移除，即通过 Iterator.remove、Set.remove、removeAll、retainAll 和 clear 操作从映射中移除相应的映射。
     * 它不支持 add 或 addAll 操作。
     *
     * @return 此映射中包含的映射的集合视图
     */
    @Override
    public Set<Entry<K, V>> entrySet() {
        Set<Entry<K, V>> es;
        return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
    }

    @Override
    public V getOrDefault(Object key, V defaultValue) {
        Node<K, V> e;
        return (e = getNode(hash(key), key)) == null ? defaultValue : e.value;
    }

    /**
     * 如果该 map 中不包含给定的 key 序列，则将该序列插入到 map 中
     *
     * @param key   key
     * @param value key对应的值
     *
     * @return null
     */
    @Override
    public V putIfAbsent(K key, V value) {
        return putVal(hash(key), key, value, true, true);
    }

    @Override
    public boolean remove(Object key, Object value) {
        return removeNode(hash(key), key, value, true, true) != null;
    }

    @Override
    public boolean replace(K key, V oldValue, V newValue) {
        V v;
        Node<K, V> e;
        if ((e = getNode(hash(key), key)) != null && ((v = e.value) == oldValue || (v != null && v.equals(oldValue)))) {
            e.value = newValue;
            afterNodeAccess(e);
            return true;
        }
        return false;
    }

    // JDK8 Map 扩展方法的覆盖

    @Override
    public V replace(K key, V value) {
        Node<K, V> e;
        if ((e = getNode(hash(key), key)) != null) {
            V oldValue = e.value;
            e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
        return null;
    }

    @Override
    public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
        if (mappingFunction == null) {
            throw new NullPointerException();
        }
        int n, i;
        int binCount = 0;
        int hash = hash(key);
        Node<K, V>[] tab;
        Node<K, V> first;
        Node<K, V> old = null;
        TreeNode<K, V> t = null;
        // 触发扩容机制
        if (size > threshold || (tab = table) == null || (n = tab.length) == 0) {
            n = (tab = resize()).length;
        }
        // 通过hash计算的数组地址不为空则尝试寻找给定key的节点
        if ((first = tab[i = (n - 1) & hash]) != null) {
            // 该节点为红黑树节点
            if (first instanceof TreeNode) {
                old = (t = (TreeNode<K, V>) first).getTreeNode(hash, key);
            } else {                                     // 该节点为链表节点
                K k;
                Node<K, V> e = first;
                // 在链表中寻找给定Key值的节点
                do {
                    if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) {
                        old = e;
                        break;
                    }
                    ++binCount;
                } while ((e = e.next) != null);
            }
            // 现存节点的值
            V oldValue;
            // 如果给定Key的节点存在，且该节点的Value不为null，则直接返回该Value
            if (old != null && (oldValue = old.value) != null) {
                afterNodeAccess(old);
                return oldValue;
            }
        }
        // 计算给定表达式的值
        V v = mappingFunction.apply(key);
        // 如果 (给定节点不存在 或 给定节点的值为null) 且 (给定表达式的值为null)，则直接返回null
        if (v == null) {
            return null;
        } else if (old != null) {
            // 如果 (给定节点的值为null) 且 (给定表达式的值不为null)，则将表达式的值赋值给该节点，并返回该值
            old.value = v;
            afterNodeAccess(old);
            return v;
        } else if (t != null) {
            // 如果 (给定节点的值为null) 且 (该节点应该存在于红黑树中) 且 (给定表达式的值不为null)，则将表达式的值赋值给该节点，并返回该值
            t.putTreeVal(this, tab, hash, key, v);
        } else {
            // 如果 (给定节点的值为null) 且 (该节点应该存在于链表中) 且 (给定表达式的值不为null)，则将表达式的值赋值给该节点，并返回该值
            tab[i] = newNode(hash, key, v, first);
            if (binCount >= TREEIFY_THRESHOLD - 1) {
                treeifyBin(tab, hash);
            }
        }
        ++modCount;
        ++size;
        afterNodeInsertion(true);
        return v;
    }

    @Override
    public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
        if (remappingFunction == null) {
            throw new NullPointerException();
        }
        V oldValue;
        Node<K, V> e;
        int hash = hash(key);
        // 给定节点存在 且 该节点值不为空
        if ((e = getNode(hash, key)) != null && (oldValue = e.value) != null) {
            V v = remappingFunction.apply(key, oldValue);
            // 如果 mappingFunction 计算的值不为空则将该值赋给该节点；否则删除该节点
            if (v != null) {
                e.value = v;
                afterNodeAccess(e);
                return v;
            } else {
                removeNode(hash, key, null, false, true);
            }
        }
        return null;
    }

    @Override
    public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
        if (remappingFunction == null) {
            throw new NullPointerException();
        }
        int n, i;
        Node<K, V>[] tab;
        Node<K, V> first;
        int binCount = 0;
        int hash = hash(key);
        Node<K, V> old = null;
        TreeNode<K, V> t = null;
        // 触发扩容机制
        if (size > threshold || (tab = table) == null || (n = tab.length) == 0) {
            n = (tab = resize()).length;
        }
        // 通过hash计算的数组地址不为空则尝试寻找给定key的节点
        if ((first = tab[i = (n - 1) & hash]) != null) {
            if (first instanceof TreeNode) {                         // 红黑树节点
                old = (t = (TreeNode<K, V>) first).getTreeNode(hash, key);
            } else {                               // 非红黑树节点
                Node<K, V> e = first;
                K k;
                do {
                    if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k)))) {
                        old = e;
                        break;
                    }
                    ++binCount;
                } while ((e = e.next) != null);
            }
        }
        // 当前map不存在给定key的节点
        V oldValue = (old == null) ? null : old.value;
        V v = remappingFunction.apply(key, oldValue);                   // 计算给定的表达式的值
        if (old != null) {                        // 判断当前map是否存在给定key的节点
            if (v != null) {                      // 计算的表达式不为null，则将改值赋给当前节点
                old.value = v;
                afterNodeAccess(old);
            } else {                              // 如果表达式计算的值为null，则删除该节点
                removeNode(hash, key, null, false, true);
            }
        } else if (v != null) {                   // map中不存在给定的key的节点 && 表达式计算的值不为null
            if (t != null) {
                t.putTreeVal(this, tab, hash, key, v);
            } else {                              // 新建立一个节点并放入到map中
                tab[i] = newNode(hash, key, v, first);
                if (binCount >= TREEIFY_THRESHOLD - 1) {
                    treeifyBin(tab, hash);
                }
            }
            ++modCount;
            ++size;
            afterNodeInsertion(true);
        }
        return v;
    }

    @Override
    public V merge(K key, V value,
                   BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
        if (value == null) {
            throw new NullPointerException();
        }
        if (remappingFunction == null) {
            throw new NullPointerException();
        }
        int n, i;
        Node<K, V>[] tab;
        Node<K, V> first;
        int binCount = 0;
        int hash = hash(key);
        Node<K, V> old = null;
        TreeNode<K, V> t = null;
        // 触发扩容机制
        if (size > threshold || (tab = table) == null || (n = tab.length) == 0) {
            n = (tab = resize()).length;
        }
        // 通过hash计算的数组地址不为空则尝试寻找给定key的节点
        if ((first = tab[i = (n - 1) & hash]) != null) {
            if (first instanceof TreeNode) {
                old = (t = (TreeNode<K, V>) first).getTreeNode(hash, key);
            } else {
                Node<K, V> e = first;
                K k;
                do {
                    if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) {
                        old = e;
                        break;
                    }
                    ++binCount;
                } while ((e = e.next) != null);
            }
        }
        // 如果map中存在该节点
        if (old != null) {
            V v;
            // 如果该节点的值不为空，则将 remappingFunction 计算的值赋给该节点；否则讲给定的 value 值赋给该节点
            if (old.value != null) {
                v = remappingFunction.apply(old.value, value);
            } else {
                v = value;
            }
            if (v != null) {
                old.value = v;
                afterNodeAccess(old);
            } else {
                // 如果赋值后该节点的值为空，则删除该节点
                removeNode(hash, key, null, false, true);
            }
            return v;
        }
        // 如果 map 中不存在该节点，则添加该节点，并最终返回 value 的值
        if (t != null) {
            t.putTreeVal(this, tab, hash, key, value);
        } else {
            tab[i] = newNode(hash, key, value, first);
            if (binCount >= TREEIFY_THRESHOLD - 1) {
                treeifyBin(tab, hash);
            }
        }
        ++modCount;
        ++size;
        afterNodeInsertion(true);
        return value;
    }

    @Override
    public void forEach(BiConsumer<? super K, ? super V> action) {
        Node<K, V>[] tab;
        if (action == null) {
            throw new NullPointerException();
        }
        if (size > 0 && (tab = table) != null) {
            int mc = modCount;
            for (Node<K, V> kvNode : tab) {
                for (Node<K, V> e = kvNode; e != null; e = e.next) {
                    action.accept(e.key, e.value);
                }
            }
            if (modCount != mc) {
                throw new ConcurrentModificationException();
            }
        }
    }

    @Override
    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
        Node<K, V>[] tab;
        if (function == null) {
            throw new NullPointerException();
        }
        if (size > 0 && (tab = table) != null) {
            int mc = modCount;
            for (Node<K, V> kvNode : tab) {
                for (Node<K, V> e = kvNode; e != null; e = e.next) {
                    e.value = function.apply(e.key, e.value);
                }
            }
            if (modCount != mc) {
                throw new ConcurrentModificationException();
            }
        }
    }

    /**
     * Returns a shallow copy of this HashMapSource</tt> instance: the keys and
     * values themselves are not cloned.
     *
     * @return a shallow copy of this map
     */
    @Override
    public Object clone() {
        HashMapSource<K, V> result;
        try {
            result = (HashMapSource<K, V>) super.clone();
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
        result.reinitialize();
        result.putMapEntries(this, false);
        return result;
    }

    // These methods are also used when serializing HashSets
    final float loadFactor() {
        return loadFactor;
    }

    final int capacity() {
        return (table != null) ? table.length :
                (threshold > 0) ? threshold :
                        DEFAULT_INITIAL_CAPACITY;
    }

    /**
     * Save the state of the HashMapSource</tt> instance to a stream (i.e.,
     * serialize it).
     *
     * @serialData The <i>capacity</i> of the HashMapSource (the length of the
     * bucket array) is emitted (int), followed by the
     * <i>size</i> (an int, the number of key-value
     * mappings), followed by the key (Object) and value (Object)
     * for each key-value mapping.  The key-value mappings are
     * emitted in no particular order.
     */
    private void writeObject(java.io.ObjectOutputStream s)
            throws IOException {
        int buckets = capacity();
        // Write out the threshold, loadfactor, and any hidden stuff
        s.defaultWriteObject();
        s.writeInt(buckets);
        s.writeInt(size);
        internalWriteEntries(s);
    }

    /* ------------------------------------------------------------ */
    // Cloning and serialization

    /**
     * Reconstitutes this map from a stream (that is, deserializes it).
     *
     * @param s the stream
     *
     * @throws ClassNotFoundException if the class of a serialized object
     *                                could not be found
     * @throws IOException            if an I/O error occurs
     */
    private void readObject(java.io.ObjectInputStream s)
            throws IOException, ClassNotFoundException {
        // Read in the threshold (ignored), loadfactor, and any hidden stuff
        s.defaultReadObject();
        reinitialize();
        if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
            throw new InvalidObjectException("Illegal load factor: " +
                    loadFactor);
        }
        s.readInt();                // Read and ignore number of buckets
        int mappings = s.readInt(); // Read number of mappings (size)
        if (mappings < 0) {
            throw new InvalidObjectException("Illegal mappings count: " +
                    mappings);
        } else if (mappings > 0) { // (if zero, use defaults)
            // Size the table using given load factor only if within
            // range of 0.25...4.0
            float lf = Math.min(Math.max(0.25f, loadFactor), 4.0f);
            float fc = (float) mappings / lf + 1.0f;
            int cap = ((fc < DEFAULT_INITIAL_CAPACITY) ?
                    DEFAULT_INITIAL_CAPACITY :
                    (fc >= MAXIMUM_CAPACITY) ?
                            MAXIMUM_CAPACITY :
                            tableSizeFor((int) fc));
            float ft = (float) cap * lf;
            threshold = ((cap < MAXIMUM_CAPACITY && ft < MAXIMUM_CAPACITY) ?
                    (int) ft : Integer.MAX_VALUE);

            // Check Entry[].class since it's the nearest public type to
            // what we're actually creating.
            SharedSecrets.getJavaOISAccess().checkArray(s, Entry[].class, cap);
            table = (Node<K, V>[]) new Node[cap];

            // Read the keys and values, and put the mappings in the HashMapSource
            for (int i = 0; i < mappings; i++) {
                K key = (K) s.readObject();
                V value = (V) s.readObject();
                putVal(hash(key), key, value, false, false);
            }
        }
    }

    // Create a regular (non-tree) node
    Node<K, V> newNode(int hash, K key, V value, Node<K, V> next) {
        return new Node<>(hash, key, value, next);
    }

    // For conversion from TreeNodes to plain nodes
    Node<K, V> replacementNode(Node<K, V> p, Node<K, V> next) {
        return new Node<>(p.hash, p.key, p.value, next);
    }

    // Create a tree bin node
    TreeNode<K, V> newTreeNode(int hash, K key, V value, Node<K, V> next) {
        return new TreeNode<>(hash, key, value, next);
    }

    // 对于 treeifyBin
    TreeNode<K, V> replacementTreeNode(Node<K, V> p, Node<K, V> next) {
        return new TreeNode<>(p.hash, p.key, p.value, next);
    }

    /* ------------------------------------------------------------ */
    // iterators

    /**
     * Reset to initial default state.  Called by clone and readObject.
     */
    void reinitialize() {
        table = null;
        entrySet = null;
        keySet = null;
        values = null;
        modCount = 0;
        threshold = 0;
        size = 0;
    }

    // 回调以允许 LinkedHashMap 后操作
    void afterNodeAccess(Node<K, V> p) {
    }

    void afterNodeInsertion(boolean evict) {
    }

    void afterNodeRemoval(Node<K, V> p) {
    }

    /* ------------------------------------------------------------ */
    // spliterators

    // Called only from writeObject, to ensure compatible ordering.
    void internalWriteEntries(java.io.ObjectOutputStream s) throws IOException {
        Node<K, V>[] tab;
        if (size > 0 && (tab = table) != null) {
            for (Node<K, V> kvNode : tab) {
                for (Node<K, V> e = kvNode; e != null; e = e.next) {
                    s.writeObject(e.key);
                    s.writeObject(e.value);
                }
            }
        }
    }

    /**
     * 基本哈希 bin 节点，用于大多数条目。（请参阅下面的 TreeNode 子类，以及 LinkedHashMap 中的 Entry 子类。）
     */
    static class Node<K, V> implements Entry<K, V> {
        final int hash;
        final K key;

        V value;
        Node<K, V> next;

        Node(int hash, K key, V value, Node<K, V> next) {
            this.key = key;
            this.hash = hash;
            this.value = value;
            this.next = next;
        }

        @Override
        public final K getKey() {
            return key;
        }

        @Override
        public final V getValue() {
            return value;
        }

        @Override
        public final String toString() {
            return key + "=" + value;
        }

        @Override
        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        @Override
        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        @Override
        public final boolean equals(Object obj) {
            if (obj == this) {
                return true;
            }
            if (obj instanceof Entry) {
                Entry<?, ?> entry = (Entry<?, ?>) obj;
                return Objects.equals(key, entry.getKey()) &&
                        Objects.equals(value, entry.getValue());
            }
            return false;
        }
    }

    static class HashMapSpliterator<K, V> {
        final HashMapSource<K, V> map;
        Node<K, V> current;          // current node
        int index;                  // current index, modified on advance/split
        int fence;                  // one past last index
        int est;                    // size estimate
        int expectedModCount;       // for comodification checks

        HashMapSpliterator(HashMapSource<K, V> m, int origin,
                           int fence, int est,
                           int expectedModCount) {
            this.map = m;
            this.index = origin;
            this.fence = fence;
            this.est = est;
            this.expectedModCount = expectedModCount;
        }

        final int getFence() { // initialize fence and size on first use
            int hi;
            if ((hi = fence) < 0) {
                HashMapSource<K, V> m = map;
                est = m.size;
                expectedModCount = m.modCount;
                Node<K, V>[] tab = m.table;
                hi = fence = (tab == null) ? 0 : tab.length;
            }
            return hi;
        }

        public final long estimateSize() {
            getFence(); // force init
            return est;
        }
    }

    static final class KeySpliterator<K, V>
            extends HashMapSpliterator<K, V>
            implements Spliterator<K> {
        KeySpliterator(HashMapSource<K, V> m, int origin, int fence, int est,
                       int expectedModCount) {
            super(m, origin, fence, est, expectedModCount);
        }

        @Override
        public KeySpliterator<K, V> trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            return (lo >= mid || current != null) ? null :
                    new KeySpliterator<>(map, lo, index = mid, est >>>= 1,
                            expectedModCount);
        }

        @Override
        public void forEachRemaining(Consumer<? super K> action) {
            int i, hi, mc;
            if (action == null) {
                throw new NullPointerException();
            }
            HashMapSource<K, V> m = map;
            Node<K, V>[] tab = m.table;
            if ((hi = fence) < 0) {
                mc = expectedModCount = m.modCount;
                hi = fence = (tab == null) ? 0 : tab.length;
            } else {
                mc = expectedModCount;
            }
            if (tab != null && tab.length >= hi &&
                    (i = index) >= 0 && (i < (index = hi) || current != null)) {
                Node<K, V> p = current;
                current = null;
                do {
                    if (p == null) {
                        p = tab[i++];
                    } else {
                        action.accept(p.key);
                        p = p.next;
                    }
                } while (p != null || i < hi);
                if (m.modCount != mc) {
                    throw new ConcurrentModificationException();
                }
            }
        }

        @Override
        public boolean tryAdvance(Consumer<? super K> action) {
            int hi;
            if (action == null) {
                throw new NullPointerException();
            }
            Node<K, V>[] tab = map.table;
            if (tab != null && tab.length >= (hi = getFence()) && index >= 0) {
                while (current != null || index < hi) {
                    if (current == null) {
                        current = tab[index++];
                    } else {
                        K k = current.key;
                        current = current.next;
                        action.accept(k);
                        if (map.modCount != expectedModCount) {
                            throw new ConcurrentModificationException();
                        }
                        return true;
                    }
                }
            }
            return false;
        }

        @Override
        public int characteristics() {
            return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) |
                    Spliterator.DISTINCT;
        }
    }

    /* ------------------------------------------------------------ */
    // LinkedHashMap support


    /*
     * The following package-protected methods are designed to be
     * overridden by LinkedHashMap, but not by any other subclass.
     * Nearly all other internal methods are also package-protected
     * but are declared final, so can be used by LinkedHashMap, view
     * classes, and HashSet.
     */

    static final class ValueSpliterator<K, V> extends HashMapSpliterator<K, V> implements Spliterator<V> {
        ValueSpliterator(HashMapSource<K, V> m, int origin, int fence, int est, int expectedModCount) {
            super(m, origin, fence, est, expectedModCount);
        }

        @Override
        public ValueSpliterator<K, V> trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            return (lo >= mid || current != null) ? null :
                    new ValueSpliterator<>(map, lo, index = mid, est >>>= 1,
                            expectedModCount);
        }

        @Override
        public void forEachRemaining(Consumer<? super V> action) {
            int i, hi, mc;
            if (action == null) {
                throw new NullPointerException();
            }
            HashMapSource<K, V> m = map;
            Node<K, V>[] tab = m.table;
            if ((hi = fence) < 0) {
                mc = expectedModCount = m.modCount;
                hi = fence = (tab == null) ? 0 : tab.length;
            } else {
                mc = expectedModCount;
            }
            if (tab != null && tab.length >= hi &&
                    (i = index) >= 0 && (i < (index = hi) || current != null)) {
                Node<K, V> p = current;
                current = null;
                do {
                    if (p == null) {
                        p = tab[i++];
                    } else {
                        action.accept(p.value);
                        p = p.next;
                    }
                } while (p != null || i < hi);
                if (m.modCount != mc) {
                    throw new ConcurrentModificationException();
                }
            }
        }

        @Override
        public boolean tryAdvance(Consumer<? super V> action) {
            int hi;
            if (action == null) {
                throw new NullPointerException();
            }
            Node<K, V>[] tab = map.table;
            if (tab != null && tab.length >= (hi = getFence()) && index >= 0) {
                while (current != null || index < hi) {
                    if (current == null) {
                        current = tab[index++];
                    } else {
                        V v = current.value;
                        current = current.next;
                        action.accept(v);
                        if (map.modCount != expectedModCount) {
                            throw new ConcurrentModificationException();
                        }
                        return true;
                    }
                }
            }
            return false;
        }

        @Override
        public int characteristics() {
            return (fence < 0 || est == map.size ? Spliterator.SIZED : 0);
        }
    }

    static final class EntrySpliterator<K, V> extends HashMapSpliterator<K, V> implements Spliterator<Entry<K, V>> {
        EntrySpliterator(HashMapSource<K, V> m, int origin, int fence, int est, int expectedModCount) {
            super(m, origin, fence, est, expectedModCount);
        }

        @Override
        public EntrySpliterator<K, V> trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            return (lo >= mid || current != null) ? null :
                    new EntrySpliterator<>(map, lo, index = mid, est >>>= 1,
                            expectedModCount);
        }

        @Override
        public void forEachRemaining(Consumer<? super Entry<K, V>> action) {
            int i, hi, mc;
            if (action == null) {
                throw new NullPointerException();
            }
            HashMapSource<K, V> m = map;
            Node<K, V>[] tab = m.table;
            if ((hi = fence) < 0) {
                mc = expectedModCount = m.modCount;
                hi = fence = (tab == null) ? 0 : tab.length;
            } else {
                mc = expectedModCount;
            }
            if (tab != null && tab.length >= hi &&
                    (i = index) >= 0 && (i < (index = hi) || current != null)) {
                Node<K, V> p = current;
                current = null;
                do {
                    if (p == null) {
                        p = tab[i++];
                    } else {
                        action.accept(p);
                        p = p.next;
                    }
                } while (p != null || i < hi);
                if (m.modCount != mc) {
                    throw new ConcurrentModificationException();
                }
            }
        }

        @Override
        public boolean tryAdvance(Consumer<? super Entry<K, V>> action) {
            int hi;
            if (action == null) {
                throw new NullPointerException();
            }
            Node<K, V>[] tab = map.table;
            if (tab != null && tab.length >= (hi = getFence()) && index >= 0) {
                while (current != null || index < hi) {
                    if (current == null) {
                        current = tab[index++];
                    } else {
                        Node<K, V> e = current;
                        current = current.next;
                        action.accept(e);
                        if (map.modCount != expectedModCount) {
                            throw new ConcurrentModificationException();
                        }
                        return true;
                    }
                }
            }
            return false;
        }

        @Override
        public int characteristics() {
            return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) |
                    Spliterator.DISTINCT;
        }
    }

    /**
     * Entry for Tree bins. Extends LinkedHashMap.Entry (which in turn
     * extends Node) so can be used as extension of either regular or
     * linked node.
     */
    static final class TreeNode<K, V> extends LinkedHashMapSource.Entry<K, V> {
        TreeNode<K, V> parent;  // red-black tree links
        TreeNode<K, V> left;
        TreeNode<K, V> right;
        TreeNode<K, V> prev;    // needed to unlink next upon deletion
        boolean red;

        TreeNode(int hash, K key, V val, Node<K, V> next) {
            super(hash, key, val, next);
        }

        /**
         * Ensures that the given root is the first node of its bin.
         */
        static <K, V> void moveRootToFront(Node<K, V>[] tab, TreeNode<K, V> root) {
            int n;
            if (root != null && tab != null && (n = tab.length) > 0) {
                int index = (n - 1) & root.hash;
                TreeNode<K, V> first = (TreeNode<K, V>) tab[index];
                if (root != first) {
                    Node<K, V> rn;
                    tab[index] = root;
                    TreeNode<K, V> rp = root.prev;
                    if ((rn = root.next) != null) {
                        ((TreeNode<K, V>) rn).prev = rp;
                    }
                    if (rp != null) {
                        rp.next = rn;
                    }
                    if (first != null) {
                        first.prev = root;
                    }
                    root.next = first;
                    root.prev = null;
                }
                assert checkInvariants(root);
            }
        }

        /**
         * 当 hashCode 相等且不可比较时，用于对插入进行排序的打破平局实用程序。我们不需要总顺序，
         * 只需要一致的插入规则来保持重新平衡之间的等效性。超出必要的打破平局会稍微简化测试。
         */
        static int tieBreakOrder(Object a, Object b) {
            int d;
            if (a == null || b == null ||
                    (d = a.getClass().getName().
                            compareTo(b.getClass().getName())) == 0) {
                d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
                        -1 : 1);
            }
            return d;
        }

        static <K, V> TreeNode<K, V> rotateLeft(TreeNode<K, V> root,
                                                TreeNode<K, V> p) {
            TreeNode<K, V> r, pp, rl;
            if (p != null && (r = p.right) != null) {
                if ((rl = p.right = r.left) != null) {
                    rl.parent = p;
                }
                if ((pp = r.parent = p.parent) == null) {
                    (root = r).red = false;
                } else if (pp.left == p) {
                    pp.left = r;
                } else {
                    pp.right = r;
                }
                r.left = p;
                p.parent = r;
            }
            return root;
        }

        static <K, V> TreeNode<K, V> rotateRight(TreeNode<K, V> root,
                                                 TreeNode<K, V> p) {
            TreeNode<K, V> l, pp, lr;
            if (p != null && (l = p.left) != null) {
                if ((lr = p.left = l.right) != null) {
                    lr.parent = p;
                }
                if ((pp = l.parent = p.parent) == null) {
                    (root = l).red = false;
                } else if (pp.right == p) {
                    pp.right = l;
                } else {
                    pp.left = l;
                }
                l.right = p;
                p.parent = l;
            }
            return root;
        }

        static <K, V> TreeNode<K, V> balanceInsertion(TreeNode<K, V> root,
                                                      TreeNode<K, V> x) {
            x.red = true;
            for (TreeNode<K, V> xp, xpp, xppl, xppr; ; ) {
                if ((xp = x.parent) == null) {
                    x.red = false;
                    return x;
                } else if (!xp.red || (xpp = xp.parent) == null) {
                    return root;
                }
                if (xp == (xppl = xpp.left)) {
                    if ((xppr = xpp.right) != null && xppr.red) {
                        xppr.red = false;
                        xp.red = false;
                        xpp.red = true;
                        x = xpp;
                    } else {
                        if (x == xp.right) {
                            root = rotateLeft(root, x = xp);
                            xpp = (xp = x.parent) == null ? null : xp.parent;
                        }
                        if (xp != null) {
                            xp.red = false;
                            if (xpp != null) {
                                xpp.red = true;
                                root = rotateRight(root, xpp);
                            }
                        }
                    }
                } else {
                    if (xppl != null && xppl.red) {
                        xppl.red = false;
                        xp.red = false;
                        xpp.red = true;
                        x = xpp;
                    } else {
                        if (x == xp.left) {
                            root = rotateRight(root, x = xp);
                            xpp = (xp = x.parent) == null ? null : xp.parent;
                        }
                        if (xp != null) {
                            xp.red = false;
                            if (xpp != null) {
                                xpp.red = true;
                                root = rotateLeft(root, xpp);
                            }
                        }
                    }
                }
            }
        }

        static <K, V> TreeNode<K, V> balanceDeletion(TreeNode<K, V> root,
                                                     TreeNode<K, V> x) {
            for (TreeNode<K, V> xp, xpl, xpr; ; ) {
                if (x == null || x == root) {
                    return root;
                } else if ((xp = x.parent) == null) {
                    x.red = false;
                    return x;
                } else if (x.red) {
                    x.red = false;
                    return root;
                } else if ((xpl = xp.left) == x) {
                    if ((xpr = xp.right) != null && xpr.red) {
                        xpr.red = false;
                        xp.red = true;
                        root = rotateLeft(root, xp);
                        xpr = (xp = x.parent) == null ? null : xp.right;
                    }
                    if (xpr == null) {
                        x = xp;
                    } else {
                        TreeNode<K, V> sl = xpr.left, sr = xpr.right;
                        if ((sr == null || !sr.red) &&
                                (sl == null || !sl.red)) {
                            xpr.red = true;
                            x = xp;
                        } else {
                            if (sr == null || !sr.red) {
                                sl.red = false;
                                xpr.red = true;
                                root = rotateRight(root, xpr);
                                xpr = (xp = x.parent) == null ?
                                        null : xp.right;
                            }
                            if (xpr != null) {
                                xpr.red = (xp != null) && xp.red;
                                if ((sr = xpr.right) != null) {
                                    sr.red = false;
                                }
                            }
                            if (xp != null) {
                                xp.red = false;
                                root = rotateLeft(root, xp);
                            }
                            x = root;
                        }
                    }
                } else { // symmetric
                    if (xpl != null && xpl.red) {
                        xpl.red = false;
                        xp.red = true;
                        root = rotateRight(root, xp);
                        xpl = (xp = x.parent) == null ? null : xp.left;
                    }
                    if (xpl == null) {
                        x = xp;
                    } else {
                        TreeNode<K, V> sl = xpl.left, sr = xpl.right;
                        if ((sl == null || !sl.red) &&
                                (sr == null || !sr.red)) {
                            xpl.red = true;
                            x = xp;
                        } else {
                            if (sl == null || !sl.red) {
                                if (sr != null) {
                                    sr.red = false;
                                }
                                xpl.red = true;
                                root = rotateLeft(root, xpl);
                                xpl = (xp = x.parent) == null ?
                                        null : xp.left;
                            }
                            if (xpl != null) {
                                xpl.red = (xp != null) && xp.red;
                                if ((sl = xpl.left) != null) {
                                    sl.red = false;
                                }
                            }
                            if (xp != null) {
                                xp.red = false;
                                root = rotateRight(root, xp);
                            }
                            x = root;
                        }
                    }
                }
            }
        }

        /**
         * Recursive invariant check
         */
        static <K, V> boolean checkInvariants(TreeNode<K, V> t) {
            TreeNode<K, V> tp = t.parent, tl = t.left, tr = t.right,
                    tb = t.prev, tn = (TreeNode<K, V>) t.next;
            if (tb != null && tb.next != t) {
                return false;
            }
            if (tn != null && tn.prev != t) {
                return false;
            }
            if (tp != null && t != tp.left && t != tp.right) {
                return false;
            }
            if (tl != null && (tl.parent != t || tl.hash > t.hash)) {
                return false;
            }
            if (tr != null && (tr.parent != t || tr.hash < t.hash)) {
                return false;
            }
            if (t.red && tl != null && tl.red && tr != null && tr.red) {
                return false;
            }
            if (tl != null && !checkInvariants(tl)) {
                return false;
            }
            return tr == null || checkInvariants(tr);
        }

        /**
         * Returns root of tree containing this node.
         */
        TreeNode<K, V> root() {
            for (TreeNode<K, V> r = this, p; ; ) {
                if ((p = r.parent) == null) {
                    return r;
                }
                r = p;
            }
        }

        /**
         * Finds the node starting at root p with the given hash and key.
         * The kc argument caches comparableClassFor(key) upon first use
         * comparing keys.
         */
        TreeNode<K, V> find(int h, Object k, Class<?> kc) {
            TreeNode<K, V> p = this;
            do {
                int ph, dir;
                K pk;
                TreeNode<K, V> pl = p.left, pr = p.right, q;
                if ((ph = p.hash) > h) {
                    p = pl;
                } else if (ph < h) {
                    p = pr;
                } else if ((pk = p.key) == k || (k != null && k.equals(pk))) {
                    return p;
                } else if (pl == null) {
                    p = pr;
                } else if (pr == null) {
                    p = pl;
                } else if ((kc != null ||
                        (kc = comparableClassFor(k)) != null) &&
                        (dir = compareComparables(kc, k, pk)) != 0) {
                    p = (dir < 0) ? pl : pr;
                } else if ((q = pr.find(h, k, kc)) != null) {
                    return q;
                } else {
                    p = pl;
                }
            } while (p != null);
            return null;
        }

        /**
         * Calls find for root node.
         */
        TreeNode<K, V> getTreeNode(int h, Object k) {
            return ((parent != null) ? root() : this).find(h, k, null);
        }

        /* ------------------------------------------------------------ */
        // 红黑树方法，全部改编自CLR

        /**
         * 形成从此节点链接的节点的树。
         */
        void treeify(Node<K, V>[] tab) {
            TreeNode<K, V> root = null;
            for (TreeNode<K, V> x = this, next; x != null; x = next) {
                next = (TreeNode<K, V>) x.next;
                x.left = x.right = null;
                if (root == null) {
                    x.parent = null;
                    x.red = false;
                    root = x;
                } else {
                    K k = x.key;
                    int h = x.hash;
                    Class<?> kc = null;
                    for (TreeNode<K, V> p = root; ; ) {
                        int dir, ph;
                        K pk = p.key;
                        if ((ph = p.hash) > h) {
                            dir = -1;
                        } else if (ph < h) {
                            dir = 1;
                        } else if ((kc == null &&
                                (kc = comparableClassFor(k)) == null) ||
                                (dir = compareComparables(kc, k, pk)) == 0) {
                            dir = tieBreakOrder(k, pk);
                        }

                        TreeNode<K, V> xp = p;
                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
                            x.parent = xp;
                            if (dir <= 0) {
                                xp.left = x;
                            } else {
                                xp.right = x;
                            }
                            root = balanceInsertion(root, x);
                            break;
                        }
                    }
                }
            }
            moveRootToFront(tab, root);
        }

        /**
         * 返回替换从该节点链接的非 TreeNode 的列表。
         */
        Node<K, V> untreeify(HashMapSource<K, V> map) {
            Node<K, V> hd = null, tl = null;
            for (Node<K, V> q = this; q != null; q = q.next) {
                Node<K, V> p = map.replacementNode(q, null);
                if (tl == null) {
                    hd = p;
                } else {
                    tl.next = p;
                }
                tl = p;
            }
            return hd;
        }

        /**
         * putVal 的树版本。
         */
        TreeNode<K, V> putTreeVal(HashMapSource<K, V> map, Node<K, V>[] tab,
                                  int h, K k, V v) {
            Class<?> kc = null;
            boolean searched = false;
            TreeNode<K, V> root = (parent != null) ? root() : this;
            for (TreeNode<K, V> p = root; ; ) {
                int dir, ph;
                K pk;
                if ((ph = p.hash) > h) {
                    dir = -1;
                } else if (ph < h) {
                    dir = 1;
                } else if ((pk = p.key) == k || (k != null && k.equals(pk))) {
                    return p;
                } else if ((kc == null &&
                        (kc = comparableClassFor(k)) == null) ||
                        (dir = compareComparables(kc, k, pk)) == 0) {
                    if (!searched) {
                        TreeNode<K, V> q, ch;
                        searched = true;
                        if (((ch = p.left) != null &&
                                (q = ch.find(h, k, kc)) != null) ||
                                ((ch = p.right) != null &&
                                        (q = ch.find(h, k, kc)) != null)) {
                            return q;
                        }
                    }
                    dir = tieBreakOrder(k, pk);
                }

                TreeNode<K, V> xp = p;
                if ((p = (dir <= 0) ? p.left : p.right) == null) {
                    Node<K, V> xpn = xp.next;
                    TreeNode<K, V> x = map.newTreeNode(h, k, v, xpn);
                    if (dir <= 0) {
                        xp.left = x;
                    } else {
                        xp.right = x;
                    }
                    xp.next = x;
                    x.parent = x.prev = xp;
                    if (xpn != null) {
                        ((TreeNode<K, V>) xpn).prev = x;
                    }
                    moveRootToFront(tab, balanceInsertion(root, x));
                    return null;
                }
            }
        }

        /**
         * Removes the given node, that must be present before this call.
         * This is messier than typical red-black deletion code because we
         * cannot swap the contents of an interior node with a leaf
         * successor that is pinned by "next" pointers that are accessible
         * independently during traversal. So instead we swap the tree
         * linkages. If the current tree appears to have too few nodes,
         * the bin is converted back to a plain bin. (The test triggers
         * somewhere between 2 and 6 nodes, depending on tree structure).
         */
        void removeTreeNode(HashMapSource<K, V> map, Node<K, V>[] tab,
                            boolean movable) {
            int n;
            if (tab == null || (n = tab.length) == 0) {
                return;
            }
            int index = (n - 1) & hash;
            TreeNode<K, V> first = (TreeNode<K, V>) tab[index], root = first, rl;
            TreeNode<K, V> succ = (TreeNode<K, V>) next, pred = prev;
            if (pred == null) {
                tab[index] = first = succ;
            } else {
                pred.next = succ;
            }
            if (succ != null) {
                succ.prev = pred;
            }
            if (first == null) {
                return;
            }
            if (root.parent != null) {
                root = root.root();
            }
            if (root == null
                    || (movable
                    && (root.right == null
                    || (rl = root.left) == null
                    || rl.left == null))) {
                tab[index] = first.untreeify(map);  // too small
                return;
            }
            TreeNode<K, V> p = this, pl = left, pr = right, replacement;
            if (pl != null && pr != null) {
                TreeNode<K, V> s = pr, sl;
                while ((sl = s.left) != null) // find successor
                {
                    s = sl;
                }
                boolean c = s.red;
                s.red = p.red;
                p.red = c; // swap colors
                TreeNode<K, V> sr = s.right;
                TreeNode<K, V> pp = p.parent;
                if (s == pr) { // p was s's direct parent
                    p.parent = s;
                    s.right = p;
                } else {
                    TreeNode<K, V> sp = s.parent;
                    if ((p.parent = sp) != null) {
                        if (s == sp.left) {
                            sp.left = p;
                        } else {
                            sp.right = p;
                        }
                    }
                    if ((s.right = pr) != null) {
                        pr.parent = s;
                    }
                }
                p.left = null;
                if ((p.right = sr) != null) {
                    sr.parent = p;
                }
                if ((s.left = pl) != null) {
                    pl.parent = s;
                }
                if ((s.parent = pp) == null) {
                    root = s;
                } else if (p == pp.left) {
                    pp.left = s;
                } else {
                    pp.right = s;
                }
                if (sr != null) {
                    replacement = sr;
                } else {
                    replacement = p;
                }
            } else if (pl != null) {
                replacement = pl;
            } else if (pr != null) {
                replacement = pr;
            } else {
                replacement = p;
            }
            if (replacement != p) {
                TreeNode<K, V> pp = replacement.parent = p.parent;
                if (pp == null) {
                    root = replacement;
                } else if (p == pp.left) {
                    pp.left = replacement;
                } else {
                    pp.right = replacement;
                }
                p.left = p.right = p.parent = null;
            }

            TreeNode<K, V> r = p.red ? root : balanceDeletion(root, replacement);

            if (replacement == p) {  // detach
                TreeNode<K, V> pp = p.parent;
                p.parent = null;
                if (pp != null) {
                    if (p == pp.left) {
                        pp.left = null;
                    } else if (p == pp.right) {
                        pp.right = null;
                    }
                }
            }
            if (movable) {
                moveRootToFront(tab, r);
            }
        }

        /**
         * 将树箱中的节点拆分为下树箱和上树箱，或者如果现在太小则取消树化。仅从调整大小调用；见上面关于分割位和索引的讨论。
         *
         * @param map   the map
         * @param tab   the table for recording bin heads
         * @param index 被拆分的表的索引
         * @param bit   要拆分的哈希值
         */
        void split(HashMapSource<K, V> map, Node<K, V>[] tab, int index, int bit) {
            TreeNode<K, V> b = this;
            // 重新链接到 lo 和 hi 列表，保留顺序
            TreeNode<K, V> loHead = null, loTail = null;
            TreeNode<K, V> hiHead = null, hiTail = null;
            int lc = 0, hc = 0;
            for (TreeNode<K, V> e = b, next; e != null; e = next) {
                next = (TreeNode<K, V>) e.next;
                e.next = null;
                if ((e.hash & bit) == 0) {
                    if ((e.prev = loTail) == null) {
                        loHead = e;
                    } else {
                        loTail.next = e;
                    }
                    loTail = e;
                    ++lc;
                } else {
                    if ((e.prev = hiTail) == null) {
                        hiHead = e;
                    } else {
                        hiTail.next = e;
                    }
                    hiTail = e;
                    ++hc;
                }
            }

            if (loHead != null) {
                if (lc <= UNTREEIFY_THRESHOLD) {
                    tab[index] = loHead.untreeify(map);
                } else {
                    tab[index] = loHead;
                    if (hiHead != null) // (else is already treeified)
                    {
                        loHead.treeify(tab);
                    }
                }
            }
            if (hiHead != null) {
                if (hc <= UNTREEIFY_THRESHOLD) {
                    tab[index + bit] = hiHead.untreeify(map);
                } else {
                    tab[index + bit] = hiHead;
                    if (loHead != null) {
                        hiHead.treeify(tab);
                    }
                }
            }
        }
    }

    final class KeySet extends AbstractSet<K> {
        @Override
        public int size() {
            return size;
        }

        @Override
        public void clear() {
            this.clear();
        }

        @Override
        public Iterator<K> iterator() {
            return new KeyIterator();
        }

        @Override
        public boolean contains(Object o) {
            return containsKey(o);
        }

        @Override
        public boolean remove(Object key) {
            return removeNode(hash(key), key, null, false, true) != null;
        }

        @Override
        public Spliterator<K> spliterator() {
            return new KeySpliterator<>(HashMapSource.this, 0, -1, 0, 0);
        }

        @Override
        public void forEach(Consumer<? super K> action) {
            Node<K, V>[] tab;
            if (action == null) {
                throw new NullPointerException();
            }
            if (size > 0 && (tab = table) != null) {
                int mc = modCount;
                for (Node<K, V> kvNode : tab) {
                    for (Node<K, V> e = kvNode; e != null; e = e.next) {
                        action.accept(e.key);
                    }
                }
                if (modCount != mc) {
                    throw new ConcurrentModificationException();
                }
            }
        }
    }

    final class Values extends AbstractCollection<V> {
        @Override
        public int size() {
            return size;
        }

        @Override
        public void clear() {
            this.clear();
        }

        @Override
        public Iterator<V> iterator() {
            return new ValueIterator();
        }

        @Override
        public boolean contains(Object o) {
            return containsValue(o);
        }

        @Override
        public Spliterator<V> spliterator() {
            return new ValueSpliterator<>(HashMapSource.this, 0, -1, 0, 0);
        }

        @Override
        public void forEach(Consumer<? super V> action) {
            Node<K, V>[] tab;
            if (action == null) {
                throw new NullPointerException();
            }
            if (size > 0 && (tab = table) != null) {
                int mc = modCount;
                for (Node<K, V> kvNode : tab) {
                    for (Node<K, V> e = kvNode; e != null; e = e.next) {
                        action.accept(e.value);
                    }
                }
                if (modCount != mc) {
                    throw new ConcurrentModificationException();
                }
            }
        }
    }

    final class EntrySet extends AbstractSet<Entry<K, V>> {
        @Override
        public int size() {
            return size;
        }

        @Override
        public void clear() {
            this.clear();                                               // IDEA检查其会发生无限调用自身
        }

        @Override
        public Iterator<Entry<K, V>> iterator() {
            return new EntryIterator();
        }

        @Override
        public boolean contains(Object o) {
            if (!(o instanceof Entry)) {
                return false;
            }
            Entry<?, ?> e = (Entry<?, ?>) o;
            Object key = e.getKey();
            Node<K, V> candidate = getNode(hash(key), key);
            return candidate != null && candidate.equals(e);
        }

        @Override
        public boolean remove(Object o) {
            if (o instanceof Entry) {
                Entry<?, ?> e = (Entry<?, ?>) o;
                Object key = e.getKey();
                Object value = e.getValue();
                return removeNode(hash(key), key, value, true, true) != null;
            }
            return false;
        }

        @Override
        public Spliterator<Entry<K, V>> spliterator() {
            return new EntrySpliterator<>(HashMapSource.this, 0, -1, 0, 0);
        }

        @Override
        public void forEach(Consumer<? super Entry<K, V>> action) {
            Node<K, V>[] tab;
            if (action == null) {
                throw new NullPointerException();
            }
            if (size > 0 && (tab = table) != null) {
                int mc = modCount;
                for (Node<K, V> kvNode : tab) {
                    for (Node<K, V> e = kvNode; e != null; e = e.next) {
                        action.accept(e);
                    }
                }
                if (modCount != mc) {
                    throw new ConcurrentModificationException();
                }
            }
        }
    }

    abstract class HashIterator {
        Node<K, V> next;        // next entry to return
        Node<K, V> current;     // current entry
        int expectedModCount;  // for fast-fail
        int index;             // current slot

        HashIterator() {
            expectedModCount = modCount;
            Node<K, V>[] t = table;
            current = next = null;
            index = 0;
            if (t != null && size > 0) { // advance to first entry
                do {
                    // do nothing
                    System.out.println("一个空代码块");
                } while (index < t.length && (next = t[index++]) == null);
            }
        }

        public final boolean hasNext() {
            return next != null;
        }

        final Node<K, V> nextNode() {
            Node<K, V>[] t;
            Node<K, V> e = next;
            if (modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
            if (e == null) {
                throw new NoSuchElementException();
            }
            if ((next = (current = e).next) == null && (t = table) != null) {
                do {
                } while (index < t.length && (next = t[index++]) == null);
            }
            return e;
        }

        public final void remove() {
            Node<K, V> p = current;
            if (p == null) {
                throw new IllegalStateException();
            }
            if (modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
            current = null;
            K key = p.key;
            removeNode(hash(key), key, null, false, false);
            expectedModCount = modCount;
        }
    }

    final class KeyIterator extends HashIterator implements Iterator<K> {
        @Override
        public K next() {
            return nextNode().key;
        }
    }

    final class ValueIterator extends HashIterator implements Iterator<V> {
        @Override
        public V next() {
            return nextNode().value;
        }
    }

    /* ------------------------------------------------------------ */
    // Tree bins

    final class EntryIterator extends HashIterator implements Iterator<Entry<K, V>> {
        @Override
        public Entry<K, V> next() {
            return nextNode();
        }
    }
}
